package com.xujl.fastlib.base;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.xujl.fastlib.http.ApiDisposableObserver;
import com.xujl.fastlib.http.BaseResponse;
import com.xujl.fastlib.http.NetworkManager;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;

/**
 * @author xujl
 * @email 597355068@qq.com
 * @Date on 2019/6/18
 * @Description
 */
public abstract class BaseModel implements LifecycleObserver {
    private final String TAG = getClass().getSimpleName();
    //管理RxJava，主要针对RxJava异步操作造成的内存泄漏
    private List<DisposableObserver> mCompositeDisposable = new ArrayList<>();
    private WeakReference<LifecycleProvider> mLifeWeakReference;

    public BaseModel () {
    }

    public abstract void init (IControl control);

    /**
     * 注入RxLifecycle生命周期
     *
     * @param lifecycle
     */
    public void injectLifecycleProvider (LifecycleProvider lifecycle) {
        this.mLifeWeakReference = new WeakReference<>(lifecycle);
    }

    public <T> void request (Observable<BaseResponse<T>> observable, ApiDisposableObserver<T> observer) {
        NetworkManager.execute(observable, observer);
        mCompositeDisposable.add(observer);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void onAny (LifecycleOwner owner, Lifecycle.Event event) {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate () {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy () {
        if (mCompositeDisposable != null) {
            for (DisposableObserver observer : mCompositeDisposable) {
                observer.dispose();
            }
            mCompositeDisposable.clear();
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart () {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop () {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume () {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause () {
    }
}
